define(function(require){
  const Handlebars = require('handlebars')
  const $ = require('jquery')
  const earth = require('app/earth')

  let $backbtn = $('#page-search .back-btn')
  let $leftnav = $('#page-search .leftnav')
  let $articleList = $('#page-search .articleList')
  let $listcon = $('#page-search .articleList .listcon')

  let $page = $('#page-search .page')
  let $webglBgRound = $('#webgl-bg-round')

  let tpl_list = Handlebars.compile($('#tpl-search-list').html())

  let inited = false

  let start = {
    minDate: '1990-06-16 23:59:59', //设定最小日期为当前日期
      //festival:true,
    maxDate: $.nowDate({DD:0}), //最大日期
    choosefun: function(elem,datas){
      end.minDate = datas; //开始日选好后，重置结束日的最小日期
    }
  }
  let end = {
    minDate: $.nowDate({DD:0}), //设定最小日期为当前日期
    maxDate: '2099-06-16 23:59:59', //最大日期
    choosefun: function(elem,datas){
      start.maxDate = datas; //将结束日的初始值设定为开始日的最大日期
    }
  }

  function init(){
    $("#start").jeDate(start)
    $("#end").jeDate(end)
    $backbtn.on('click', function(){history.back()})
    $('#start,#end').on('click',function(){
      setTimeout(function(){
        $('.jedatebox').addClass('show')
      },100)
    })
    $("input[name='search-lnav0']").on('change',function(){
        $articleList.removeClass('show')
        renderDetailList()
    })
    $('.scont').on('click',function(){
      $('#start').val('')
      $('#end').val('')        
    })
    $("input[name='search-lnav1']").on('change',function(){
      $articleList.removeClass('show')
      sessionStorage.timetype=$(this).val()
      let type=$(this).val()
      let nowTime=new Date()
      let startTime=nowTime.getFullYear() + '-'
      let endTime='';
      let weekdata=new Date(nowTime.getTime() - 7 * 24 * 3600 * 1000);
      let monthdata=new Date(nowTime.getTime() - 30 * 24 * 3600 * 1000);
      if(type==0){
        startTime=nowTime.getFullYear() + '-' +((nowTime.getMonth() + 1)<10? '0'+ (nowTime.getMonth()+1):(nowTime.getMonth()+1)) + '-' + (nowTime.getDate()<10? '0' + nowTime.getDate():nowTime.getDate()) + ' ' + '00:00:00'
        endTime= nowTime.getFullYear() + '-' + ((nowTime.getMonth() + 1)<10? '0'+ (nowTime.getMonth()+1):(nowTime.getMonth()+1)) + '-'+ (nowTime.getDate()<10? '0' + nowTime.getDate():nowTime.getDate()) + ' '+ '23:59:59'
      }else if(type==1){
        startTime=weekdata.getFullYear() + '-' +((weekdata.getMonth() + 1)<10? '0'+ (weekdata.getMonth()+1):(weekdata.getMonth()+1)) + '-' + (weekdata.getDate()<10? '0' + weekdata.getDate():weekdata.getDate()) + ' ' + '00:00:00'
        endTime=  nowTime.getFullYear() + '-' + ((nowTime.getMonth() + 1)<10? '0'+ (nowTime.getMonth()+1):(nowTime.getMonth()+1)) + '-' + (nowTime.getDate()<10?'0'+nowTime.getDate():nowTime.getDate()) + ' ' + '23:59:59'
      }else if(type==2){
        startTime=monthdata.getFullYear() + '-' +((monthdata.getMonth() + 1)<10? '0'+ (monthdata.getMonth()+1):(monthdata.getMonth()+1)) + '-' + (monthdata.getDate()<10? '0' + monthdata.getDate():monthdata.getDate()) + ' ' + '00:00:00'
        endTime=nowTime.getFullYear() + '-' + ((nowTime.getMonth() + 1)<10? '0'+ (nowTime.getMonth()+1):(nowTime.getMonth()+1)) + '-' + (nowTime.getDate()<10?'0'+nowTime.getDate():nowTime.getDate()) + ' ' + '23:59:59'
      }else{
          startTime=""
      }
      $('#start').val(startTime)
      $('#end').val(endTime)
      renderDetailList()
    })  
    $("#start").val(sessionStorage.startTime)
    $("#end").val(sessionStorage.endTime)
    $("input[name='search-lnav0']").each(function(){
      if($(this).val()==sessionStorage.type){
          $(this).attr('checked',true)
      }
    })
    $("input[name='search-lnav1']").each(function(){
      if($(this).val()==sessionStorage.timetype){
          $(this).attr('checked',true)
      }
    })
    $('#head-right-search>input').val(sessionStorage.wd)
  }

  function routeIn(from){
    $('#head-right-search').addClass('center')
    if(!earth.showingDetail){
      earth.showDetailView()
      earth.timeline.hide()
    }
    $leftnav.addClass('show')
    $page.addClass('show')
    $backbtn.addClass('show')
    if(from != 'details'){
      earth.$cont.addClass('moveRight')
      $webglBgRound.addClass('moveRight')
      $('#star-bg').removeClass('hide')
    }
    if(from == 'home'){
      earth.earthRotate(true)
    }
    if(!inited){
      inited = true
      init()
    }
    renderDetailList()
    //查询按钮
    $('.searchbtn,.sure button').on('click',function(){
      renderDetailList()
    })
    //回车事件
    $('#head-right-search>input').on('keypress',function(event){
      if(event.keyCode=="13"){
        $articleList.removeClass('show')
        renderDetailList()
      }  
    })
  }

  async function routeOut(to){
    $backbtn.removeClass('show')   
    $leftnav.removeClass('show')
    $articleList.removeClass('show')
    $page.removeClass('show')
    if(to != 'details'){
      earth.$cont.removeClass('moveRight')
      earth.hideDetailView()
      $webglBgRound.removeClass('moveRight')      
      $('#star-bg').addClass('hide')
    }
    if(to == 'home'){
      earth.earthRotate(false)
    }
    $('.searchbtn,.sure button').off('click')
    $('#head-right-search>input').off('keypress')
  }
  
  //分页-查询商品
  window.ChangePage=async function(type, total, pagesize, currentpage,m){
  let page = ChangePageCheck(type, total, pagesize, currentpage, m)
      $articleList.addClass('show')
  let out = {}
  if(page){
      let data={
        startTime:$('#start').val(),
        endTime:$('#end').val(),
        type:$("input[name='search-lnav0']:checked").val(),
        wd:$('#head-right-search>input').val(),
        currentPage:page,
        page:5
      }
      if(data.startTime.length<19 && data.startTime.length>=16){
          data.startTime=data.startTime+":00"
      }
      if(data.endTime.length<19 && data.endTime.length>=16){
          data.endTime=data.endTime+":00"
      }
      out.obj= (await searchInfo('page',data)).obj.list
      $listcon.html(tpl_list(out))
  }
}
  /*
* 分页模块
*参数：total:数据总数量,pagesize:每页显示数目，currentpage:当前页,m:显示页数
*/
function pageshow(total,pagesize,currentpage,m){
    let totalpage = Math.ceil(total / pagesize) //总页数
    let k = Math.ceil(totalpage / m)
    let pagehtml='' 
    let pagehtmlstart=''
    let pagehtmlmiddle=''
    let pagehtmlend=''
    //上一页
    pagehtmlstart='<li id="prevPage" onclick="ChangePage('+ '\'prePage\','+total+','+pagesize+','+currentpage+','+ m +')"><a>上一页</a></li>'
    //下一页
    pagehtmlend='<li id="nextPage" onclick="ChangePage('+ '\'nextPage\','+total+','+pagesize+','+currentpage+','+ m +')"></a>下一页</a></li>'
    if(m<=1){
      pagehtmlmiddle='<li class="active"><a>'+ currentpage +'</a></li>'
    }
    else if(m>1){
        if (totalpage > m) {//总页数多余显示的页数
            if(currentpage>m){
                pagehtmlstart='<li id="prevPage" onclick="ChangePage('+ '\'prePage\','+total+','+pagesize+','+currentpage+','+ m +')"><a>上一页</a></li>'
            }
            if (currentpage <= (k - 1) * m){
                pagehtmlend='<li id="nextPage" onclick="ChangePage('+ '\'nextPage\','+total+','+pagesize+','+currentpage+','+ m +')"><a>下一页</a></li>'
            }
        }
    }
    //计算显示页码
    var k1 = Math.floor((currentpage-1) / m)
    for (var i = 1; i < m+1; i++){
      var pagenum = i + k1 * m;
          if (pagenum > totalpage) {
              break;
          }
          if (currentpage == pagenum){
            pagehtmlmiddle +='<li class="active"><a>' + currentpage + '</a></li>'
          }else{
            pagehtmlmiddle +='<li onclick="ChangePage('+ '\'mpage\','+total+','+pagesize+','+pagenum+','+ m +')"><a>'+ pagenum +'</a></li>'
          }
    }
    //页面显示
    if(totalpage==1){
          pagehtml=" "
    }else{
        pagehtml = pagehtmlstart + pagehtmlmiddle + pagehtmlend;
    }
    
    $('.page ul').empty();
    $('.page ul').append(pagehtml)
    //设置分页按钮是否可点击
    if(currentpage<=1){
      $('#prevPage').hide()
    }
    if(totalpage <= 1 || currentpage >= totalpage){
      $('#nextPage').hide()
    }

}
  //分页按钮点击
  function ChangePageCheck(type,total,pagesize,currentpage,m){
    $articleList.removeClass('show')
      var  page = 1;
      let totalpage = Math.ceil(total / pagesize); //总页数
      if(type=="prePage"){ //上一页
        if (parseInt(currentpage) > 1){
            page = parseInt(currentpage) - 1;
        } else {
            $("#prePage").hide();
            return false
              }
        } else if(type=='mpage'){
            page = currentpage
        }
        else if(type=='nextPage'){
          if(parseInt(currentpage) < parseInt(totalpage)){
            page = parseInt(currentpage)+1 
          }else if(parseInt(currentpage) == parseInt(totalpage)){
            $("#nextPage").hide() 
            return false
          }
        }
        return page;
  }
  //时间处理
  window.tiemChange=function(value){
        value=new Date(parseInt(value)); 
        let M  = (value.getMonth()+1 < 10 ? '0'+(value.getMonth()+1) : value.getMonth()+1) + '-';
        let D = (value.getDate() <10 ? '0' + value.getDate():value.getDate())+ ' ';
        let h = (value.getHours() <10 ? '0' + value.getHours():value.getHours())+ ':';
        let m = value.getMinutes() <10 ? '0' + value.getMinutes():value.getMinutes();
        return M + D + h + m
  }
  //查询按钮
  async function searchInfo(type,data){
      Handlebars.registerHelper("trans",function(value){
        value=new Date(parseInt(value)); 
        let M  = (value.getMonth()+1 < 10 ? '0'+(value.getMonth()+1) : value.getMonth()+1) + '-';
        let D = (value.getDate() <10 ? '0' + value.getDate():value.getDate())+ ' ';
        let h = (value.getHours() <10 ? '0' + value.getHours():value.getHours())+ ':';
        let m = value.getMinutes() <10 ? '0' + value.getMinutes():value.getMinutes();
        return M + D + h + m
      })
      Handlebars.registerHelper('typetrs',function(value){
        if(value==1){
          return '法规'
        }else if(value==2){
          return '标准'
        }else if(value==3){
          return '技术'
        }else if(value==4){
            return '威胁'
        }else if(value==5){
          return '新闻事件'
        }
      })
      let res = await $.post('api/collection/queryInfos',data,function(result){
          if(result.success){
              $articleList.addClass('show')   
              let obj=eval(data)
              if (type == "page") {//如果是分页-查询商品 
                pageshow(result.obj.total,result.obj.pageSize,obj.currentPage,2)
              }else if(type == "search"){
                pageshow(result.obj.total,result.obj.pageSize,1,2)
              }
          }
      })
      return res
  }
  //列表点击
  window.clickart=function(id){
    window.location.href="./#details/?id=" + id + ""
  }
  //查询
  async function renderDetailList(){
    let out = {}
    let data={
      startTime:$('#start').val(),
      endTime:$('#end').val(),
      type:$("input[name='search-lnav0']:checked").val(),
      wd:$('#head-right-search>input').val(),
      currentPage:1,
      page:5
    }
    if(data.startTime.length<19 && data.startTime.length>=16){
        data.startTime=data.startTime+":00"
    }
    if(data.endTime.length<19 && data.endTime.length>=16){
        data.endTime=data.endTime+":00"
    }
    let nowTime=new Date()
    let startStrime=nowTime.getFullYear() + '-' +((nowTime.getMonth() + 1)<10? '0'+ (nowTime.getMonth()+1):(nowTime.getMonth()+1)) + '-' + (nowTime.getDate()<10? '0' + nowTime.getDate():nowTime.getDate()) + ' ' + '00:00:00'
    let endTime=nowTime.getFullYear() + '-' +((nowTime.getMonth() + 1)<10? '0'+ (nowTime.getMonth()+1):(nowTime.getMonth()+1)) + '-' + (nowTime.getDate()<10? '0' + nowTime.getDate():nowTime.getDate()) + ' ' + '59:59:59'
    if(data.startTime==""){
      data.startTime=startStrime
    }
    if(data.endTime==""){
      data.endTime=endTime
    }  
    sessionStorage.startTime=data.startTime;
    sessionStorage.endTime=data.endTime
    sessionStorage.type=data.type
    sessionStorage.wd=data.wd
    sessionStorage.currentPage=data.currentPage
    sessionStorage.page=data.page
    out.obj= (await searchInfo('search',data)).obj.list
    if(out.obj.length!=0 || out.obj.length!=''){
        $listcon.html(tpl_list(out))
    }else{
      $('.listcon').empty()
      $('.listcon').append('<div class="datanull">没有相关数据</div>')
    }
  }
  return {routeIn, routeOut}
})